var q = require('q');
var request = require('request').defaults({
    json: true
});
var config = require('./../config.json');

function queryConvergence(params) {
    var defer = q.defer();
    request({
        url: config.apiUrl + '/recentchanges',
        qs: params
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve(JSON.parse(body));
        } else {
            defer.resolve(null);
        }
    });
    return defer.promise;
}
var toString = function (searchType) {
    var unit = searchType === 'design' ? "cm" : 'mm';
    var _this = this;
    if (_this.type === 'less') {
        return '< ' + this.max + ' ' + unit;
    } else if (_this.type === 'between') {
        return this.min + ' ~ ' + this.max + ' ' + unit;
    } else {
        return '> ' + this.min + ' ' + unit;
    }
};

var filterByCondition = function (conditions, result, searchType) {
    searchType = searchType || 'design';
    var total = result.curValues.length;
    var filterResults = conditions.map(function (conditionItem) {
        var matchData = [];
        //查询设计值变化
        if (searchType === 'design') {
            matchData = result.curValues.filter(function (item) {
                var value = Math.abs(item.value) / 10.0;// 转化成厘米
                return (value >= conditionItem.min) && (value < conditionItem.max);
            });
        } else if (searchType === 'diff') {//查询累计变化
            matchData = result.curValues.filter(function (item, index) {
                var value = Math.abs(item.value - result.lastValues[index].value);
                return (value >= conditionItem.min) && (value < conditionItem.max);
            });
        }

        return {
            count: matchData.length,
            text: toString.call(conditionItem, searchType),
            ratio: ((matchData.length / total) * 100).toFixed(2) + '%'
        };
    });
    return filterResults;
};

//处理收敛统计查询
exports.postConvergence = function (postData) {
    var _this = this;
    var defer = q.defer();
    var deferArray = postData.locationList.map(function (item, index) {
        return queryConvergence({
            type: '收敛',
            location: item,
            isDesign: postData.isDesign,
            prjId: _this.prjId,
            time1: postData.startTime || (postData.startTimeList ? postData.startTimeList[index] : undefined),
            time2: postData.endTime || (postData.endTimeList ? postData.startTimeList[index] : undefined),
            fuzzy: postData.fuzzy || undefined
        });
    });

    q.all(deferArray).then(function (resultArray) {
        var results = resultArray.map(function (result, index) {
            //最终返回该数组
            return {
                title: result.title + "设计值统计",
                datas: filterByCondition(postData.conditions, result, postData.searchType),
                location: postData.locationList[index],
                allTimes: result.allTimes,
                count: result.pointsCount,
                tunnelType: _this.tunnelType,
                maxPointThisTime: _this._extendRingMileage(result, result.maxPointThisTime),
                minPointThisTime: _this._extendRingMileage(result, result.minPointThisTime),
                maxPointAllTheTime: _this._extentMaxMinResultPoint(result, result.maxPointAllTheTime),//最大变化
                minPointAllTheTime: _this._extentMaxMinResultPoint(result, result.minPointAllTheTime)//最小变化
            };
        });
        results = results.filter(function (item) {
            return item.count > 0;
        });
        defer.resolve(results);
    });
    return defer.promise;
};

exports._extendRingMileage = function (result, maxorminPoint) {
    if (!maxorminPoint) return undefined;
    var _this = this;
    maxorminPoint.value = maxorminPoint.value.toFixed(1);
    maxorminPoint.ringNumber = maxorminPoint.ringNumber || '未配置';
    maxorminPoint.mileage = maxorminPoint.mileage || '未配置';
    var designValue = 5.5;
    switch (_this.tunnelType) {
        case "单圆隧道":
            designValue = 5.5;
            break;
        case "双圆隧道":
            designValue = 4.975;
            break;
        default:
            break;
    }
    //获取本次和上次测值
    result.curValues.some(function (item) {
        if (item.name === maxorminPoint.name) {
            maxorminPoint.curValue = (item.value / 1000 + designValue).toFixed(4);
            maxorminPoint.curTime = item.time;
            return true;
        } else {
            return false;
        }
    });
    result.lastValues.some(function (item) {
        if (item.name === maxorminPoint.name) {
            maxorminPoint.lastValue = (item.value / 1000 + designValue).toFixed(4);
            maxorminPoint.lastTime = item.time;
            return true;
        } else {
            return false;
        }
    });

    return maxorminPoint;
};

exports._extentMaxMinResultPoint = function (result, maxorminPoint) {
    if (!maxorminPoint) return undefined;
    var _this = this;
    var designValue = 5.5;
    switch (_this.tunnelType) {
        case "单圆隧道":
            designValue = 5.5;
            break;
        case "双圆隧道":
            designValue = 4.975;
            break;
        case "大圆":
            designValue = 10.4;
            break;
        default:
            break;
    }
    maxorminPoint.designValue = designValue.toFixed(4);
    maxorminPoint.measureValue = (maxorminPoint.value / 1000 + designValue).toFixed(4);
    maxorminPoint.ringNumber = maxorminPoint.ringNumber || '未配置';
    maxorminPoint.mileage = maxorminPoint.mileage || '未配置';
    maxorminPoint.value = maxorminPoint.value.toFixed(1);
    //获取本次和上次测值
    result.curValues.some(function (item) {
        if (item.name === maxorminPoint.name) {
            maxorminPoint.time = item.time;
            return true;
        } else {
            return false;
        }
    });
    return maxorminPoint;
};

//根据监测类型获取LocationList
exports.getLocationList = function (type) {
    var defer = q.defer();
    var _this = this;
    request({
        url: config.apiUrl + '/LocationList',
        qs: {
            prjId: _this.prjId,
            type: type
        }
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            defer.resolve(body);
        } else {
            defer.resolve(null);
        }
    });
    return defer.promise;
};
